<?php

namespace app\common\service;

use app\admin\model\ConsultWork;
use app\admin\model\XwqlRecord;
use app\admin\model\XwqlWork;
use think\facade\Db;

class CommonService
{
    public static function getWorkStatus(){
        $statusArr=[
            '1'=>'待村级预受理',//未处理
            '2'=>'待村级受理',//已预受理，待受理
            '3'=>'待村级办理',//已受理，待办理
            '4'=>'待乡镇预受理',
            '5'=>'待乡镇受理',
            '6'=>'待乡镇办理',
            '7'=>'待部门预受理',
            '8'=>'待部门受理',
            '9'=>'待部门办理',
            '10'=>'已通过',
            '11'=>'用户已取消',
            '-1'=>'村级未通过',
            '-2'=>'乡镇未通过',
            '-3'=>'部门未通过',
        ];
        return $statusArr;
    }

    public static function getHnzjCoverPhoto(){
        preg_match('/(.*\.)?\w+\.\w+$/', $_SERVER['SERVER_NAME'], $matches);
        $domain = '';
        if (!empty($matches[1])) {
            $domain = $matches[1];
        }
        $coverPhoto=[
            '1'=>'http://image.xwql.zmjjjc.gov.cn/upload/source/hnzj/1.jpg',
            '2'=>'http://image.xwql.zmjjjc.gov.cn/upload/source/hnzj/2.jpg',
            '3'=>'http://image.xwql.zmjjjc.gov.cn/upload/source/hnzj/3.jpg',
            '4'=>'http://image.xwql.zmjjjc.gov.cn/upload/source/hnzj/4.jpg',
        ];
        return $coverPhoto;
    }

    public static function getWorkType(){
        $typeArr=[
            '1'=>'村委会办结',
            '2'=>'乡镇办结',
            '3'=>'县直部门办结'
        ];
        return $typeArr;
    }

    public static function getCityArr(){
        $cityArr=[
            'zm.xwql.'=>['中牟','中牟县','http://image.xwql.zmjjjc.gov.cn/upload/source/zm.jpg'],
        ];
        return $cityArr;
    }

    public static function getCityName(){
        preg_match('/(.*\.)?\w+\.\w+$/', $_SERVER['SERVER_NAME'], $matches);
        $domain = '';
        if (!empty($matches[0])) {
            $domain = $matches[0];
        }
        $domain=$domain.'.';
        $name= CommonService::getCityArr()[$domain] ?? [''];
        return $name;
    }

    public static function getWxTempConfig(){
        $config=[
            'xwql_zz_zm'=>[
                'AppID' => 'wx2af88c77e55a90aa',//已改
                'AppSecret' => 'b0a4cb822bdae82bf8a8ae6bb9b6b3d7',
                'wxTmpId' => 'oTAd_EHtQ__loaerW274Zyz2gzn6dulIOWzSkYNHZ1Q',
                'wxLoginUrl' => 'https://api.weixin.qq.com/sns/jscode2session?',
                'wxAccessTokenUrl' => 'https://api.weixin.qq.com/cgi-bin/token?',
                'wxSendSubscribeUrl' => 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?'
            ],
        ];
        return $config;
    }

    public static function getSystemConfigByDomain(){
        $domainArr = [
            'zm.xwql.api.','zm.xwql.'
        ]; //七个县市
        $databaseArr = ['xwql_zz_zm'];
        $config = [
            'domainArr' => $domainArr,
            'databaseArr'=> $databaseArr,
            'config'=> []
        ];
        preg_match('/(.*\.)?\w+\.\w+$/', $_SERVER['SERVER_NAME'], $matches);
        $domain = '';
        if (!empty($matches[0])) {
            $domain = $matches[0].'.';
        }
        $domain='zm.xwql.';
        if (in_array($domain,$domainArr)){
            if (in_array($domain,['zm.xwql.','zm.xwql.api.'])){
                //里面的都没改
                $config['config']['AppID'] = 'wx2af88c77e55a90aa';
                $config['config']['AppSecret'] = 'b0a4cb822bdae82bf8a8ae6bb9b6b3d7';
                $config['config']['wxTmpId'] = 'oTAd_EHtQ__loaerW274Zyz2gzn6dulIOWzSkYNHZ1Q';
                $config['config']['wxLoginUrl'] = 'https://api.weixin.qq.com/sns/jscode2session?';
                $config['config']['wxAccessTokenUrl'] = 'https://api.weixin.qq.com/cgi-bin/token?';
                $config['config']['wxSendSubscribeUrl'] = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?';

                $config['config']['TENCENT_MESSAGE_APPID'] = '1400591929';
                $config['config']['TENCENT_MESSAGE_APPKEY'] = 'a0dbef95ba9f1e9ab7cd524765a0773e';
                $config['config']['TENCENT_MESSAGE_SIGN'] = '中牟纪委';

                $config['config']['TENCENT_MESSAGE_1'] = '1197304';
                $config['config']['TENCENT_MESSAGE_2'] = '1197311';
                $config['config']['TENCENT_MESSAGE_3'] = '1197342';
                $config['config']['TENCENT_MESSAGE_4'] = '1197366';
                $config['config']['TENCENT_MESSAGE_5'] = '1197379';
                $config['config']['TENCENT_MESSAGE_6'] = '1197389';
                $config['config']['TENCENT_MESSAGE_7'] = '1197397';
                $config['config']['TENCENT_MESSAGE_8'] = '1197410';
                //$config['config']['TENCENT_MESSAGE_9'] = '1197420'; //超时
                $config['config']['TENCENT_MESSAGE_10'] = '1197427';
                $config['config']['TENCENT_MESSAGE_11'] = '1197439';
                $config['config']['TENCENT_MESSAGE_14'] = '1185494';
                $config['config']['TENCENT_MESSAGE_15'] = '1185502';
                $config['config']['TENCENT_MESSAGE_16'] = '1185508';
            }/*elseif(in_array($domain,['jqs.'])){
                $config['config']['AppID'] = 'wx3f6dc21cf1e2cf63';
                $config['config']['AppSecret'] = 'f85a7665957227cce687188e6c86827f';
            }*/
        }else{
            echo '配置错误！';
            exit;
        }
        return $config;
    }

    public static function getXwqlFixedUrl(){
        $urlArr=[
            'zm.xwql.'=>[
                0=>[
                    'http://image.xwql.zmjjjc.gov.cn/upload/source/xwql_zz_zm/zr1.jpg',
                    'http://image.xwql.zmjjjc.gov.cn/upload/source/xwql_zz_zm/zr2.jpg',
                ],
                1=>[
                    'http://image.xwql.zmjjjc.gov.cn/upload/source/xwql_zz_zm/fx1.jpg',
                    'http://image.xwql.zmjjjc.gov.cn/upload/source/xwql_zz_zm/fx2.jpg',
                    'http://image.xwql.zmjjjc.gov.cn/upload/source/xwql_zz_zm/fx3.jpg',
                ],
                2=>[
                    'http://image.xwql.zmjjjc.gov.cn/upload/source/xwql_zz_zm/jd1.jpg',
                    'http://image.xwql.zmjjjc.gov.cn/upload/source/xwql_zz_zm/jd2.jpg',
                ],
            ]
        ];
        return $urlArr;
    }

    public static function getUserStatus(){
        return $statusArr=[
            0=>'禁用',
            1=>'正常',
        ];
    }

    public static function getPoliteComprehensiveType(){
        return $typeArr=[
            1=>'吃在乡镇分类',
            2=>'玩在乡镇分类',
            3=>'乐购乡镇分类',
            4=>'创业乡镇分类',
        ];
    }

    /*
     * 留言、办事等功能需要实名后才能操作
     * 用户是否实名逻辑
     */
    public static function checkWxUserIsRealName($user_id){
        $result = false;

        $where = [
            ['id','=',$user_id]
        ];
        $check = Db::name('wx_user')->where($where)->field('status')->find();
        if (false != $check){
            $check['status'] == 1 && $result = true;
        }
        return $result;
    }
    //计算办事是否超时及超时时间
    public static function getWorkOvertimeByWorkerman($consultWorkId){
        $breakData=self::getBreakData();
        $villageIsWarn=1;//否
        $townshipIsWarn=1;//否
        $departmentIsWarn=1;//否
        $consultWorkModel=new ConsultWork();
        $xwqlWorkModel=new XwqlWork();
        $xwqlRecordModel=new XwqlRecord();
        $consultWorkField='id,work_id,department_reply_time,township_reply_time,village_reply_time,create_time,status';
        $consultWork=$consultWorkModel->field($consultWorkField)->find($consultWorkId);
        if($consultWork['status']!=11){//用户没有取消才计算
            $xwqlWorkField='id,village_time,township_time,department_time,is_village,is_township,is_department';
            $xwqlWork=$xwqlWorkModel->field($xwqlWorkField)->find([$consultWork['work_id']]);

            $xwqlWork['village_time']=$xwqlWork['village_time']==0||empty($xwqlWork['village_time'])?86400:$xwqlWork['village_time']*86400;
            $xwqlWork['township_time']=$xwqlWork['township_time']==0||empty($xwqlWork['township_time'])?86400:$xwqlWork['township_time']*86400;
            $xwqlWork['department_time']=$xwqlWork['department_time']==0||empty($xwqlWork['department_time'])?86400:$xwqlWork['department_time']*86400;

            $currentStatus=$consultWork['status'];

            $calcPara=[
                ['is_village',3,-1,'村级超时','village_reply_time','village_time'],
                ['is_township',6,-2,'乡镇超时','township_reply_time','township_time'],
                ['is_department',9,-3,'部门超时','department_reply_time','village_time'],
            ];
            foreach ($calcPara as $k=>$v){
                if($xwqlWork[$v[0]]==2){
                    $startRecord=$xwqlRecordModel->where(['consult_work_id'=>$consultWorkId,'status'=>$v[1]])->field('create_time')->find();
                    if(!empty($startRecord)){
                        $startTime=self::getStartTime(strtotime($startRecord['create_time']),$breakData);
                        if($currentStatus>$v[1]||$currentStatus<=$v[2]){
                            $endTime=$consultWork[$v[4]];
                        }else{
                            $endTime=time();
                        }
                        $overtimePoint=self::calcOvertimePoint($startTime,$xwqlWork[$v[5]],$breakData);
                        if($endTime>$overtimePoint){
                            switch ($k){
                                case 0:
                                    $villageIsWarn=2;
                                    break;
                                case 1:
                                    $townshipIsWarn=2;
                                    break;
                                case 2:
                                    $departmentIsWarn=2;
                            }
                        }
                    }
                }
            }
        }
        $returnData['village_is_warn']=$villageIsWarn;
        $returnData['township_is_warn']=$townshipIsWarn;
        $returnData['department_is_warn']=$departmentIsWarn;
        return $returnData;
    }
    //计算办事是否超时及超时时间
    public static function getWorkOvertime($consultWorkId){
        $breakData=self::getBreakData();
        $villageIsWarn=1;//否
        $townshipIsWarn=1;//否
        $departmentIsWarn=1;//否
        $warnText='';
        $consultWorkModel=new ConsultWork();
        $xwqlWorkModel=new XwqlWork();
        $xwqlRecordModel=new XwqlRecord();

        $consultWorkField='id,work_id,department_reply_time,township_reply_time,village_reply_time,create_time,status';
        $consultWork=$consultWorkModel->field($consultWorkField)->find($consultWorkId);
        if($consultWork['status']!=11){//用户没有取消才计算
            $xwqlWorkField='id,village_time,township_time,department_time,is_village,is_township,is_department';
            $xwqlWork=$xwqlWorkModel->field($xwqlWorkField)->find([$consultWork['work_id']]);

            $xwqlWork['village_time']=$xwqlWork['village_time']==0||empty($xwqlWork['village_time'])?86400:$xwqlWork['village_time']*86400;
            $xwqlWork['township_time']=$xwqlWork['township_time']==0||empty($xwqlWork['township_time'])?86400:$xwqlWork['township_time']*86400;
            $xwqlWork['department_time']=$xwqlWork['department_time']==0||empty($xwqlWork['department_time'])?86400:$xwqlWork['department_time']*86400;

            $currentStatus=$consultWork['status'];

            $calcPara=[
                ['is_village',3,-1,'村级超时','village_reply_time','village_time'],
                ['is_township',6,-2,'乡镇超时','township_reply_time','township_time'],
                ['is_department',9,-3,'部门超时','department_reply_time','village_time'],
            ];
            foreach ($calcPara as $k=>$v){
                if($xwqlWork[$v[0]]==2){//计算村级超时
                    $startRecord=$xwqlRecordModel->where(['consult_work_id'=>$consultWorkId,'status'=>$v[1]])->field('create_time')->find();
                    if(!empty($startRecord)){
                        $startTime=self::getStartTime(strtotime($startRecord['create_time']),$breakData);
                        if($currentStatus>$v[1]||$currentStatus<=$v[2]){
                            $endTime=$consultWork[$v[4]];
                        }else{
                            $endTime=time();
                        }
                        $overtimePoint=self::calcOvertimePoint($startTime,$xwqlWork[$v[5]],$breakData);
                        if($endTime>$overtimePoint){
                            switch ($k){
                                case 0:
                                    $villageIsWarn=2;
                                    break;
                                case 1:
                                    $townshipIsWarn=2;
                                    break;
                                case 2:
                                    $departmentIsWarn=2;
                            }
                            $warnText.=$v[3].self::calcTime($overtimePoint,$endTime,$breakData).'<br/>';
                        }
                    }
                }
            }
        }
        $warnText=empty($warnText)?'--':$warnText;
        $returnData['village_is_warn']=$villageIsWarn;
        $returnData['township_is_warn']=$townshipIsWarn;
        $returnData['department_is_warn']=$departmentIsWarn;
        $returnData['warn_text']=$warnText;
        return $returnData;
    }
    //计算办事办理时长
    public static function getWorkHandleDuration($consultWorkId){
        $breakData=self::getBreakData();
        $timeText='';
        $consultWorkModel=new ConsultWork();
        $xwqlWorkModel=new XwqlWork();
        $xwqlRecordModel=new XwqlRecord();

        $consultWorkField='id,work_id,department_reply_time,township_reply_time,village_reply_time,create_time,status';
        $consultWork=$consultWorkModel->field($consultWorkField)->find($consultWorkId);
        if($consultWork['status']!=11) {//用户没有取消才计算
            $xwqlWorkField='id,is_village,is_township,is_department';
            $xwqlWork=$xwqlWorkModel->field($xwqlWorkField)->find([$consultWork['work_id']]);
            $currentStatus=$consultWork['status'];

            $calcPara=[
                ['is_village',3,-1,'村级办理','village_reply_time'],
                ['is_township',6,-2,'乡镇办理','township_reply_time'],
                ['is_department',9,-3,'部门办理','department_reply_time'],
            ];
            foreach ($calcPara as $v){
                if($xwqlWork[$v[0]]==2&&($currentStatus>$v[1]||$currentStatus<=$v[2])){//计算村级超时
                    $startRecord = $xwqlRecordModel->where(['consult_work_id' => $consultWorkId, 'status' => $v[1]])->field('create_time')->find();
                    if(!empty($startRecord)){
                        $startTime=self::getStartTime(strtotime($startRecord['create_time']),$breakData);
                        $timeText.=$v[3].self::calcTime($startTime,$consultWork[$v[4]],$breakData).'<br/>';
                    }
                }
            }
        }
        return empty($timeText)?'--':$timeText;
    }
    //获取开始时间，如果为休息日则推进至下一个最近的工作日0点
    public static function getStartTime($startTime,$breakArr){
        while ($breakArr[date('Y-m-d',$startTime)]['type']==2){
            $startTime=strtotime(date('Y-m-d',$startTime));
            $startTime+=86400;
        }

        return $startTime;
    }
    //获取工休策略
    public static function getBreakData(){
        $break=Db::connect('common')->table('ea_conf_work_break')->removeOption('where')->where([['year','in',[date('Y'),date('Y')-1,date('Y')+1]]])->select()->toArray();
        $breakArr=[];
        foreach ($break as $k=>$v){
            $breakArr=array_merge(json_decode($v['work_break'],true),$breakArr);
        }
        return $breakArr;
    }
    //根据起止时间获取并计算排除休息日的时长，单位S
    public static function calcTime($startTime,$endTime,$breakArr){
        $time=0;
        $startTime+=86400;//判断下一天
        while ($startTime<$endTime){
            if($breakArr[date('Y-m-d',$startTime)]['type']!=2){//如果为休息日
                $time+=strtotime(date('Y-m-d',$startTime));
                $startTime=strtotime(date('Y-m-d',$startTime));
            }
            $startTime+=86400;
        }
        $startTime-=86400;
        $time+=$endTime-$startTime;
        return self::Sec2Time($time);
    }
    //根据开始时间和限制时长获取超时时间点
    public static function calcOvertimePoint($startTime,$limit,$breakArr){
        $endTime=$startTime+$limit;
        while ($startTime<=$endTime){
            $startTime+=86400;
            if($breakArr[date('Y-m-d',$startTime)]['type']==2){
                $endTime+=86400;
            }
        }
        return $endTime;
    }
    //将秒格式化为时间
    public static function Sec2Time($time)
    {
        if (!is_numeric($time)) {
            return (bool) false;
        }

        $value = [
            "days" => 0, "hours" => 0,
            "minutes" => 0, "seconds" => 0,
        ];

        if ($time >= 86400) {
            $value["days"] = floor($time/86400);
            $time = ($time%86400);
        }

        if ($time >= 3600) {
            $value["hours"] = floor($time/3600);
            $time = ($time%3600);
        }

        if ($time >= 60) {
            $value["minutes"] = floor($time/60);
            $time = ($time%60);
        }

        $value["seconds"] = floor($time);

        $t = $value["days"] . "天"." ". $value["hours"] . "小时". $value["minutes"] . "分".$value["seconds"]."秒";

        return $t;
    }
}